﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Google.Documents;
using System.Threading;
using Google.GData.Client;
using ResxLocalizationEditor.GoogleImport;
using Google.GData.Documents;
using System.IO;
using System.Globalization;

namespace ResxLocalizationEditor.GoogleExport {
    partial class ExportingPanel : UserControl {
        public ExportingPanel() {
            InitializeComponent();
        }

        public void Export(string username, string password,
            ResourceSet resources, Document folder) {

            _username = username;
            _password = password;
            _resources = resources;
            _folder = folder;

            ThreadPool.QueueUserWorkItem(DoExport, null);
        }

        string _username, _password;
        ResourceSet _resources;
        Document _folder;

        private void DoExport(object o) {
            var settings = new RequestSettings(GoogleDocsImport.ApiAppKey, _username, _password);
            settings.AutoPaging = true;

            var service = new DocumentsService("ResxLocalizationEditor");
            service.setUserCredentials(_username, _password);

            UpdateGui(0, true, "Deleting folder contents...");

            var reqFolder = new DocumentsRequest(settings);
            var feedFolder = reqFolder.GetFolderContent(_folder);
            foreach (var f in feedFolder.Entries) {
                var item = service.Get("http://docs.google.com/feeds/default/private/full/" + f.ResourceId);
                item.Delete();
            }

            var tmpFile = Path.GetTempFileName();
            var writer = new CsvResourceWriter();
            var languages = _resources.Languages;
            double progressIncrement = 100.0 / (languages.Count * 2);
            double progress = 0;
            for(int i = 0; i < languages.Count; ++i){
                var lang = languages[i];

                //Dump resource to temp CSV
                UpdateGui((int)progress, false, "Writing " + lang.DisplayName + "...");
                var res = _resources[lang];
                writer.WriteSingleResource(_resources, res, tmpFile);
                progress += Math.Min(100, progressIncrement);

                //Upload
                UpdateGui((int)progress, false, "Uploading " + lang.DisplayName + "...");
                var outputName = string.Format("{0} - {1}",
                    (lang.Equals(CultureInfo.InvariantCulture)) ? "Default" : lang.Name,
                    lang.DisplayName);
                //var upDoc = service.UploadDocument(tmpFile, outputName, "text/csv");
                string folderFeed = string.Format(DocumentsListQuery.foldersUriTemplate, _folder.ResourceId);
                using (var fileStream = new FileStream(tmpFile, FileMode.Open)) {
                    service.Insert(new Uri(folderFeed), fileStream, "text/csv", outputName);
                }
                progress += Math.Min(100, progressIncrement);
            }

            UpdateGui(100, false, "Done.");
        }

        private void UpdateGui(int progress, bool marquee, string status) {
            this.Invoke(new Action(() => {
                progressBar.Style = (marquee) ? ProgressBarStyle.Marquee : ProgressBarStyle.Continuous;
                progressBar.Value = progress;
                labelStatus.Text = status;
            }));
        }
    }
}
